<?php
/*
* Author: Jason ZHENG <zmj522008@hotmil.com>
* Date  : 2018/05/18
* Class : Finance 财务报表
*/
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;

class Finance extends Controller
{ 

	public function index(Request $request)
	{ 
		$dates 		= $request->post();
		$startDate 	= isset($dates['start_date']) ? $dates['start_date'] : '1700-01-01 00:00:00';
		$endDate   	= isset($dates['end_date']) ? $dates['end_date'] : '2222-01-01 00:00:00';
		$page 		= isset($dates['page']) ? $dates['page'] : 1;

		$returnData = [
						'financeBalance' 	=> $this->get_finance_balance(),
						'ordersDetail'      => $this->get_ordersLog_by_date($startDate, $endDate, $page),
						                       
					];

		return ['code'=>666, 'msg'=>'Finance data stats/财务数据统计', 'data'=> $returnData];  
	}

	public function get_finance_balance()
	{
		return [
			'weekly'  	=> $this->get_income_receive(date('Y-m-d', strtotime('-7 days'))), // 本周：近七天
			'monthly' 	=> $this->get_income_receive(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")))), //本月
			'annually'  => $this->get_income_receive(date("Y",time()).'-01-01 00:00:00'), //今年
		];
	}

	//总收入金额（totalReceive）和支出金额（totalSpend）, 毛利润（收入-支出），占用资金（现有库存采购价）
	public function get_income_receive($date)
	{ 
		$ordersInfo = Db::table('orders')
				->alias('o')
				->join('orders_info oi','o.batchcode = oi.batchcode','LEFT')
				->where(['o.business_id' => $this->business_id, 'o.state' => 0,'oi.procurement_status' =>1])
				->where('o.createtime', '>=',$date )
				->where(['o.status' => ['neq' , 9]])
				->select();

		$totalIncome  	= 0;
		$totalSpend 	= 0;
		foreach ($ordersInfo as $order) 
		{	
			// 售出状态
			if($order['status'] === 3){
				$totalIncome  = $totalIncome + $order['total_price']+$order['nursing_income'];
				//echo $totalIncome;exit();
			}
			elseif($order['status'] === 4) // 定金支付
			{
				$totalIncome  = $totalIncome + $order['nursing_income'] + $order['deposit'];
			}
			//退款
			elseif($order['status'] === 9){
				$totalIncome = $totalIncome + $order['nursing_income'];
			}else{
				$totalIncome = $totalIncome + $order['total_price']+$order['nursing_income'] + $order['deposit'];
			}
			$totalSpend = $totalSpend + ($order['original_price'] + $order['nursing_cost']) + $order['other_fee'] + $order['fare'];
		}

		$products = Db::table('product')
				->where(['business_id' => $this->business_id, 'state' => 0,'procurement_status' =>1])
				->where(['is_shelf' => 1])
				->where('createtine', '>=',$date )
				->select();
		$productsCostTotal = 0;
		foreach ($products as $key => $product) {
			$productsCostTotal = $productsCostTotal + $product['cost_price'];
		}

		return ['totalIncome' => $totalIncome, 'totalSpend' => $totalSpend,'totalProfit' => ($totalIncome - $totalSpend), 'productsCostTotal' => $productsCostTotal ];
	}

	//获取订单详情
	public function get_ordersLog_by_date($startDate, $endDate, $page)
	{
                $product = new Product();
		$ordersInfo = Db::table('orders')
				->alias('o')
				->join('orders_info oi','o.batchcode = oi.batchcode','LEFT')
				->where(['oi.business_id' => $this->business_id, 'o.state' => 0])
				->where('o.last_time', '>=', $startDate )
				->where('o.last_time', '<=',date('Y-m-d',strtotime("$endDate +1 day")))
				->order('o.last_time desc')
				->select();
		$sales_condition = Db::table('sales_condition')->where('state',0)->select();

		$orders = [];
		foreach ($ordersInfo as $order) 
		{
			$orderLogs = Db::table('operation_log')
						->where(['module' => 'orders', 'module_id' => $order['id']])
						->order('operation_time desc')
						->select();

			foreach ($orderLogs as $orderLog) 
			{
				$operation_content = json_decode($orderLog['operation_content'],true);
				$ol = [];
				if(isset($operation_content['orders']) && isset($operation_content['orders_info']))
				{
					$ol = array_merge($operation_content['orders'],$operation_content['orders_info']);
					if($ol != $order){
						$orders [] = $ol;
					}
				}
				elseif(isset($operation_content['orders']) && !isset($operation_content['orders_info'])){
					$ol = $operation_content['orders'];
					if(array_diff($order, $ol) != null){
						$orders [] = $operation_content['orders'];
					}
				}
				elseif(!isset($operation_content['orders']) && isset($operation_content['orders_info'])){
					$ol = $operation_content['orders_info'];
					if(array_diff($order, $ol) != null){
						$orders [] = $operation_content['orders_info'];
					}
				}
			}
			$orders []= $order;
                        foreach ($orders as $pkey => $pvalue) {
                            if(array_key_exists('product_id', $pvalue)){
                                $systematics_id = Db::table('product')->alias('p')
                                    ->join('product_fineness pf','p.product_condition = pf.id', 'LEFT')
                                    ->where(array('p.id'=>$pvalue['product_id']))
                                    ->field('p.systematics_id,p.product_condition,pf.value product_condition_value')
                                    ->find();
                                $systematics_arr = $product->set_product_name($systematics_id['systematics_id']);
                                if(!$systematics_arr['data']){
                                    $orders[$pkey]['pre_name'] = '';
                                }else{
                                    $orders[$pkey]['pre_name'] = $systematics_arr['data'];
                                }
                            }
                            $orders[$pkey]['product_condition'] = $systematics_id['product_condition'];
                            $orders[$pkey]['product_condition_value'] = $systematics_id['product_condition_value'];

                            foreach ($sales_condition as $sc) {
                            	if($sc['id'] == $pvalue['status'])
                            		$orders[$pkey]['status_value'] = $sc['value'];
                            }
                            
                        }
		}
		return ['total' => count($orders), 'orders' => array_slice($orders,($page-1)*20, 20)];
	}

	//删除禁用订单
	// public function delete_order(Request $request)
	// {
	// 	$postData = $request->post();
	// 	$rules = [
	// 		'batchcode|订单号' => 'require|integer'
	// 	];
	// 	if($this->validate($postData, $rules) === true)
	// 	{
	// 		$order = Db::table('orders')
	// 				->where(['batchcode' => $postData['batchcode']])
	// 				->find();
	// 		if(empty($order)){
	// 			return ['code'=>10011, 'msg'=>'order not found|订单未找到', 'data'=> null];
	// 		}else{
	// 			Db::table('orders')
	// 				->where(['batchcode' => $postData['batchcode']])
	// 				->update(['state' => 1]);
	// 			Db::table('orders_info')
	// 				->where(['batchcode' => $postData['batchcode']])
	// 				->update(['state' => 1]);
	// 			return ['code'=>666, 'msg'=>'删除成功', 'data'=> null];
	// 			}
	// 	}else{
	// 		return ['code'=>10010, 'msg'=>$this->validate($postData, $rules), 'data'=> null];
	// 	}
	// }


}